<?php

namespace app\store\model;

use app\common\model\Goodsstock as GoodsModel;
use app\store\model\GoodsSku as GoodsSkuModel;
use app\store\service\Goods as GoodsService;

/**
 * 商品模型
 * Class Goods
 * @package app\store\model
 */
class Goodsstock extends GoodsModel
{
    /**
     * 添加商品
     * @param array $data
     * @return bool
     * @throws \think\exception\PDOException
     */
    public function add(array $data)
    {

        //$data['wxapp_id'] = $data['sku']['wxapp_id'] = self::$wxapp_id;
        $data['wxapp_id'] = self::$wxapp_id;
        $data['goods_num'] = $this->commonIdGen();
        $data['create_time'] = date("Y-m-d H:i:s");
        $data['update_time'] = date("Y-m-d H:i:s");
        // 开启事务
        $this->startTrans();
        try {
            // 添加商品
            $this->allowField(true)->save($data);
            //添加纪律
            $this->addStockLog($data,0);
            $this->commit();
            return true;
        } catch (\Exception $e) {
            $this->error = $e->getMessage();
            $this->rollback();
            return false;
        }
    }

    public  function commonIdGen(){
        return time() . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
    }

    /**
     * 添加商品图片
     * @param $images
     * @return int
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    private function addGoodsImages($images)
    {
        $this->image()->delete();
        $data = array_map(function ($image_id) {
            return [
                'image_id' => $image_id,
                'wxapp_id' => self::$wxapp_id
            ];
        }, $images);
        return $this->image()->saveAll($data);
    }

    /**
     * 编辑商品
     * @param $data
     * @return bool|mixed
     */
    public function edit($data)
    {
        $data['wxapp_id'] = self::$wxapp_id;
        $data['update_time'] = date("Y-m-d H:i:s");



        return $this->transaction(function () use ($data) {
            //查询数据
            $num = $this->where(array("goods_num"=>$data['goods_num']))->field("stock_num")->find();
            // 保存商品
            $this->allowField(true)->save($data);
            $this->editSkuLog($data,$num['stock_num']);
            return true;
        });
    }

    /**
     * 添加商品规格
     * @param $data
     * @param $isUpdate
     * @throws \Exception
     */
    private function addGoodsSpec($data, $isUpdate = false)
    {
        // 更新模式: 先删除所有规格
        $model = new GoodsSku;
        $isUpdate && $model->removeAll($this['goods_id']);
        // 添加规格数据
        if ($data['spec_type'] == '10') {
            // 单规格
            $this->sku()->save($data['sku']);
        } else if ($data['spec_type'] == '20') {
            // 添加商品与规格关系记录
            $model->addGoodsSpecRel($this['goods_id'], $data['spec_many']['spec_attr']);
            // 添加商品sku
            $model->addSkuList($this['goods_id'], $data['spec_many']['spec_list']);
        }
    }

    /**
     * 修改商品状态
     * @param $state
     * @return false|int
     */
    public function setStatus($state)
    {
        return $this->allowField(true)->save(['goods_status' => $state ? 10 : 20]) !== false;
    }

    /**
     * 软删除
     * @return false|int
     */
    public function setDelete($goodsId)
    {
        return $this->deleteData($goodsId);
    }

    /**
     * 获取当前商品总数
     * @param array $where
     * @return int|string
     * @throws \think\Exception
     */
    public function getGoodsTotal($where = [])
    {
        return $this->where('is_delete', '=', 0)->where($where)->count();
    }

    /**
     * 获取数据
     * @return false|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getGoodsStockList(){
        $lists = $this->alias('gs')->field("gs.*")
            ->join('yoshop_goods_sku g','gs.goods_num = g.goods_no','LEFT')
            ->where('g.goods_no is null')
            ->order('gs.id desc')
            ->select();
        return $lists;
    }
    /**
     * 获取数据
     * @return false|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getGoodsStockInfo($param){
        return $this->where(['id'=>$param['id']])
            ->find();
    }

    public function editSkuLog($data,$bstockNum){
        //修改库存
        $GoodsSku = new GoodsSku();
        $GoodsSku->editGoogSku(array('goods_no'=>$data['goods_num']),array('stock_num'=>$data['stock_num']));
        $this->addStockLog($data,$bstockNum);
    }

    /**
     * 添加库存日志
     * @param $data
     * @return int|string
     */
    public function addStockLog($data,$start_num=0){
        $adata = array();

        $adata['goods_no'] = $data['goods_num'];
        $adata['supplier_id'] = $data['supplier_id'];
        $adata['join_price'] = $data['join_price'];
        $adata['out_price'] = $data['out_price'];
        $adata['start_num'] = $start_num;
        $adata['end_num'] = $data['stock_num'];
        $adata['create_time'] = date("Y-m-d H:i:s");
        $adata['update_time'] = date("Y-m-d H:i:s");
        return db("goods_stock_log")->insert($adata);
    }
    /**
     * 添加库存出库商品
     * @param array $data
     * @return bool
     * @throws \think\exception\PDOException
     */
    public function addSale(array $data)
    {
        //查询出库存商品信息
        $stockInfo = $this->getGoodsStockInfo(['id'=>$data['goods_id']]);
        //计算出销售数量的成本价钱
        $data['sale_cost_price'] = $stockInfo['join_price'] * $data['sale_num'];
        //当销售总价小于成本价钱时表示录入错误 返回false
        if($data['sale_total_price'] < $data['sale_cost_price']) return false;
        //销售总价减去成本价钱等于利润
        $num = $data['sale_total_price'] - $data['sale_cost_price'];
        $data['wxapp_id'] = self::$wxapp_id;
        $data['goods_name'] = $stockInfo['goods_name'];                    //商品名称
        $data['goods_no'] = $stockInfo['goods_num'];                       //商品名称
        $data['join_price'] = $stockInfo['join_price'];                    //商品进货价
        $data['sale_profit'] = sprintf("%.2f",$num);                       //销售后利润
        $data['create_date'] = date("Y-m-d");
        $data['create_time'] = date("Y-m-d H:i:s");
        $data['update_time'] = date("Y-m-d H:i:s");
        $result = db("goods_stock_out")->insert($data);
        if($result){
            //减少库存
            db("goods_stock")->where('id',$data['goods_id'])->setDec('stock_num',$data['sale_num']);
            return true;
        }
        return false;
    }

}
